#!/bin/sh
set -e
umask 007
xd=/tmp/qubesbuilder.exporteddisks
install -m 02770 -g qubes -d "$xd"

#exec 2>>"$xd/log"
#set -x

read -r key
read -r path

if [ -z "$key" ]; then
    key=$( head -c 20 /dev/urandom | xxd -p )
    key_is_generated=1
else
    key_is_generated=
fi

test -n "$QREXEC_REMOTE_DOMAIN"
test -n "$key"
test -n "$path"

keyhash=$( echo -n "$key" | sha256sum | head -c64 )
test -n "$keyhash"
xpfile="$xd/export.$keyhash"
tmpfile=$( mktemp "$xd/tmp.XXXXXX" )
chmod 0660 "$tmpfile"

echo "$QREXEC_REMOTE_DOMAIN:$path" > "$tmpfile"
mv -f "$tmpfile" "$xpfile"

if [ -n "$key_is_generated" ]; then
    echo "$key"
fi
